﻿using LightCAD.Core;
using LightCAD.Core.Elements;
using LightCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QdArch
{
    public class QdSlab : DirectComponent, IElement3D
    {
        public List<Vector2d> OutLine { get; set; }

        public List<List<Vector2d>> Holes { get; set; }

        public List<QdUpDownSlab> UpSlabs { get; set; }
        public List<QdUpDownSlab> DownSlabs { get; set; }
        public double Thickness { get; set; }
        public double Bottom { get; set; }
        public QdSlab()
        {
            this.Type = ArchElementType.Slab;
            this.OutLine = new List<Vector2d>();
            this.Holes = new List<List<Vector2d>>();
        }

        public override Box2d GetBoundingBox()
        {
            return new Box2d().ExpandByPoints(this.OutLine.ToArray());
        }

        public override Box2d GetBoundingBox(Matrix3d matrix)
        {
            return new Box2d().ExpandByPoints(this.OutLine.Select(p => matrix.MultiplyPoint(p)).ToArray());
        }

        public override bool IntersectWithBox(Polygon2d testPoly, List<RefChildElement> intersectChildren = null)
        {
            var thisBox = this.BoundingBox;
            if (!thisBox.IntersectWith(testPoly.BoundingBox))
            {
                //如果元素盒子，与多边形盒子不相交，那就可能不相交
                return false;
            }

            var isIntersect = GeoUtils.IsPolygonIntersectPolygon(this.OutLine.ToArray(), testPoly.Points);
            if (isIntersect)
            {
                return true;
            }

            foreach (var item in this.Holes)
            {
                isIntersect = GeoUtils.IsPolygonIntersectPolygon(item.ToArray(), testPoly.Points);
                if (isIntersect)
                {
                    return true;
                }
            }
            return false;
        }

        public override bool IncludedByBox(Polygon2d testPoly, List<RefChildElement> includedChildren = null)
        {
            var thisBox = this.BoundingBox;
            if (!thisBox.IntersectWith(testPoly.BoundingBox))
            {
                return false;
            }

            return GeoUtils.IsPolygonContainsPolygon(this.OutLine.ToArray(), testPoly.Points);

        }
    }

    public class QdUpDownSlab
    {
        public QdSlab Host { get; set; }
        public double Bottom { get; set; }
        public List<Vector2d> Outline { get; set; }  = new List<Vector2d>();
        public List<Vector2d> Holes { get; set; } = new List<Vector2d>();
        public List<QdUpDownSlab> UpSlabs { get; set; } = new List<QdUpDownSlab>();
        public List<QdUpDownSlab> DownSlabs { get; set; } = new List<QdUpDownSlab>();
        public QdUpDownSlab(List<Vector2d> outline)
        {
            this.Outline = outline;
        }
    }
}
